<?php
/**
 * M2我的催收
 */

namespace app\admin\model;
use app\v2\model\Consignment;
use think\Db;

class Recoverymy extends Common
{
    protected $name = 'apply';

    /**
     * 我的回收列表
     * @param $uid
     * @param $keywords
     * @param int $page
     * @param int $limit
     * @param $valuedate
     * @param string $os
     * @param string $status
     * @return mixed
     * @throws \think\db\exception\BindParamException
     * @throws \think\exception\PDOException
     * @AUTHER 范俊成
     * @Email gakiismywife1@163.com
     * @DATE 2018/5/23
     */
    public function getDataList($uid, $keywords, $page=1, $limit=15, $valuedate, $os = '',$status = "",$filter='')
    {
        $offset = $page==1?0:($page-1)*$limit;
        $sql = "select a.huishou_status ,a.hk_time,a.id,a.order_number,c.create_time,a.status,a.name,a.phone,a.money,a.appoint_time,a.mobile_type,a.uid,a.fk_time from qh_apply a INNER JOIN qh_consignment c on c.apply_id=a.order_number where  a.huishou_aid is not null";
        $sql_count = "select a.order_number ,c.create_time from qh_apply a INNER JOIN qh_consignment c on c.apply_id=a.order_number where  a.huishou_aid is not null ";
        if($uid != 1){
            $sql .= " and a.huishou_aid = $uid";
            $sql_count .= " and a.huishou_aid = $uid";
        }
        if($os){
            $sql .= ' and os ='.$os;
            $sql_count .= ' and os ='.$os;
        }
        if($valuedate){
            $start = date('Y-m-d H:i:s',strtotime($valuedate));
            $end = date('Y-m-d H:i:s',strtotime("$valuedate +1day"));

            $sql .= " and c.create_time between '$start' and '$end'  ";
            $sql_count .= " and c.create_time between '$start' and '$end'  ";
        }
        if ($keywords){
            $sql .= " and (phone = '$keywords' or name = '$keywords' or order_number = '$keywords')";
            $sql_count .= " and (phone = '$keywords' or name = '$keywords' or order_number = '$keywords')";
        }

        if($status  != 13 && $status != 0 ){
            $sql .= " and a.status = $status";
            $sql_count .= " and a.status = $status";
        }elseif($status == 13){                                                         //已退货
            $sql .= " and c.status = 3 and a.status <> 5 ";
            $sql_count .= " and c.status = 3 and a.status <> 5 ";

        }

        //不显示驳回
        $sql .= " and huishou_status != 3 order by c.create_time desc";

        $sql_count .= " and huishou_status != 3 group by order_number";
        $sql .= ' limit '.$limit.' offset '.$offset;

        $status_detail= array('申请中','初审通过','复审通过','回收中','已违约','已完成','初审驳回','复审驳回','其他驳回','回访通过','回访拒绝','拒绝放款','续租中');

        $list = $this->query($sql);
        $dataCount = $this->query($sql_count);

        $room = array();
        //去重
        foreach ($list as $k=>$v){
            $list[$k]['huishou_way'] = '邮寄';
            $list[$k]['logistics'] = '待发货';
            if(!isset($room[$v['order_number']])){
                $room[$v['order_number']] = $k;
            }elseif (isset($room[$v['order_number']]) && (strtotime($v['create_time'])>strtotime($list[$room[$v['order_number']]]['create_time']))){
                unset($list[$room[$v['order_number']]]);
                $room[$v['order_number']] = $k;
            }else{
                unset($list[$k]);
            }
        }
        //已完成显示部门
        if($status == 5){
            foreach ($list as $k => $v){

                    if($list[$k]['hk_time'] != ''){
                        $list[$k]['dept'] = '信贷';
                    }else{
                        $list[$k]['dept'] = '回收';
                    }

            }
        }

        //已退货 显示已发货和待发货
        if($status == 13){



            $res  =$this->returnGoodsList($dataCount,$list,$status_detail);

            return $res;
        }


        //状态筛选
        if($filter && $filter == 13){
            foreach ($list as $key => $value){
                if($value['huishou_status'] != 3){
                    unset($list[$key]);
                }else{
                    $list[$key]['status'] = $status_detail[$value['status']];
                }
            }
        }elseif($filter){
            foreach ($list as $key=>$value){
                if($value['status'] != $filter){
                    unset($list[$key]);
                }else{
                    $list[$key]['status'] = $status_detail[$value['status']];
                }
            }
        }else{
            foreach ($list as $key=>$value){
                $list[$key]['status'] = $status_detail[$value['status']];
            }
        }



        $count = count($dataCount);
        $data['list'] = $list;
        $data['dataCount'] = $count;
        return $data;
    }

    /**
     * 回收通过
     * @param array $param
     * @return bool
     */
    public function createData($param)
    {
        $uid = $param['uid'];
        $discount = $param['discount'];
        $order_number = $param['order_number'];
        $id = $param['id'];

        $map['id'] = $id;
        $data = [
            'huishou_status' => 2,
            'status' => '5',
            'huishou_visit' => $discount,
            'huishou_time' => date('Y-m-d H:i:s', time())
        ];

         $this->startTrans();
        try {
            $this->save($data, $map);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->rollback();
            return false;
        }
    }

    /**
     * [xcreateData 回收驳回]
     */
    public function xcreateData($param)
    {
        $uid = $param['uid'];
        $discount = $param['discount'];
        $order_number = $param['order_number'];
        $id = $param['id'];
        $map['id'] = $id;
        $data = [
            'huishou_status' => 3,
            'huishou_visit' => $discount,
            'huishou_time' => date('Y-m-d H:i:s', time()),
        ];

        $this->startTrans();
        try {
            $this->save($data, $map);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->rollback();
            return false;
        }

    }

    /**
     * [xcreateData 退货]
     */
    public function returngoods($param)
    {
        $uid = $param['uid'];
        $order_number = $param['order_number'];
        $id = $param['id'];
        $return_no = $param['express_num'];
        $return_name = $param['express_name'];

        $map['apply_id'] = $order_number;
        $data = [
            'status' => 3,
            'return_no' => $return_no,
            'return_name' => $return_name,
            'return_time' => date('Y-m-d H:i:s', time())
        ];
        $Consign = Consignment::get(function($query) use ($map){
            $query->where($map)->order('create_time DESC');
        });
        $result = $Consign->save($data);
        if($result===false){
            $this->error = '更新失败';
            return false;
        }else{
            return true;
        }

    }

    /**
     * [更新物流]
     */
    public function updateexpress($param)
    {
        $uid = $param['uid'];
        $order_number = $param['order_number'];
        $id = $param['id'];
        $logistics_no = $param['express_num'];
        $logistics_company = $param['express_name'];

        $map['apply_id'] = $order_number;
        $data = [
            'logistics_no' => $logistics_no,
            'logistics_company' => $logistics_company,
        ];
        $result = DB::name('consignment')->where($map)->update($data);
        if($result===false){
            $this->error = '更新失败';
            return false;
        }else{
            return true;
        }
    }

    /**
     * 物流
     * @param $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @AUTHER 范俊成
     * @Email gakiismywife1@163.com
     * @DATE 2018/5/23
     */
    public function logisticsInfo($id)
    {

        $order = $this->alias('a')
            ->join('consignment c','a.order_number=c.apply_id')
            ->join('admin_user u','u.id = a.huishou_aid')
            ->where('a.id',$id)
            ->field('a.order_number,c.status,c.consignment_name,u.realname,c.consignment_phone,c.create_time time ,c.logistics_no,c.return_name,c.return_no,c.logistics_company')
            ->select();

        $order = modelo2array($order);
        $logisticData = array();
        $logisticReturnData = array();

        foreach ($order as $key => $value){
            $order[$key]['create_time'] = $value['time'];
            unset($order[$key]['time']);
            if($value['status'] != 3){
                $logisticData[] = $order[$key];
            }
            if($value['status'] == 3){
                $logisticData[] = $order[$key];
                $logisticReturnData[] = $order[$key];
            }
        }
        $data['logisticData'] = $logisticData;
        $data['logisticReturnData'] = $logisticReturnData;
        return $data;
    }

    /**
     * 已退货列表
     * @param $dataCount
     * @param $list
     * @param $status_detail
     * @return array
     * @AUTHER 范俊成
     * @Email gakiismywife1@163.com
     * @DATE 2018/5/29
     */
    public function returnGoodsList($dataCount,$list,$status_detail)
    {

        $case = array();                                                        //已发货容器

        /*根据订单号查询 是否有再发货的物流 如果有就放入$case*/
        foreach ($dataCount as $key => $value){
            $temp = $this->alias('a')
                ->join('consignment c','c.apply_id=a.order_number')
                ->field('a.order_number')
                ->where('c.create_time','>',$value['create_time'])
                ->where('c.status','<>',3)
                ->where('a.huishou_status','<>',3)
                ->where('c.apply_id',$value['order_number'])
                ->order('c.create_time desc')
                ->find();
            if($temp){
                $case[] = $temp;
            }
        }
        //对比两个array的order_number 如果有再次发货的物流,就将已退货的物流删除
        foreach ($case as $key => $value){
            foreach ($dataCount as $key1 => $value1){
                if($value['order_number'] == $value1['order_number']){
                    unset($dataCount[$key1]);
                }
            }
        }


        $house = array();    //已发货容器
        foreach ($list as $key => $value){

            //对订单号查询是否有继续发货的物流信息
            $temp = $this->alias('a')
                ->join('consignment c','c.apply_id=a.order_number')
                ->field('c.create_time time ,a.hk_time,a.id,a.order_number,c.create_time time,a.huishou_status,a.status,a.name,c.status cstatus,a.phone,a.money,a.appoint_time,a.mobile_type,a.uid,a.fk_time')
                ->where('c.create_time','>',$value['create_time'])
                ->where('c.status','<>',3)
                ->where('a.huishou_status','<>',3)
                ->where('c.apply_id',$value['order_number'])
                ->order('c.create_time desc')
                ->find();
            if($temp){
                $temp = $temp->toArray();
                if($temp['status'] == 5 && $temp['huishou_status'] == 2){
                    $temp['logistics'] = '已收货';
                }else{
                    $temp['logistics'] = '已发货';
                }
                $temp['huishou_way'] = '邮寄';
                $temp['create_time'] = $temp['time'];
                $temp['status'] = $status_detail[$temp['status']];
                $house[] = $temp;
            }
            $list[$key]['status'] = $status_detail[$value['status']];
        }


        //如果有已退货的就去除已退货的,留已发货的
        foreach ($house as $key => $value){
            foreach ($list as $key1 => $value1){
                if($value['order_number'] == $value1['order_number']){
                    unset($list[$key1]);
                }
            }
        }

        $list = array_merge($list,$house);
        //排序
        $len = count($list);
        for($i=0;$i<$len;$i++){
            for($j=0;$j<$len-$i-1;$j++){
                if(strtotime($list[$j]['create_time'])<strtotime($list[$j+1]['create_time'])){
                    $temp=$list[$j];
                    $list[$j]=$list[$j+1];
                    $list[$j+1]=$temp;
                }
            }
        }
        $dataCount = array_merge($dataCount,$case);    //所有的条数

        $data['dataCount'] = count($dataCount);

        $data['list'] =$list;
        return $data;
    }

}